package com.lcxw.hxzbapi.controller.appcontroller;


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;

import javax.annotation.Resource;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.lcxw.hxzbapi.entity.pojo.YwpdChargeDetail;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.YwpdChargeDetailService;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbapi.tencentim.common.ImCommand;
import com.lcxw.hxzbapi.tencentim.common.TencentImRealization;
import com.lcxw.hxzbcommon.common.StringUtil;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IapController {
    // 正式  购买凭证验证地址
    private static final String certificateUrl = "https://buy.itunes.apple.com/verifyReceipt";

    // 沙箱 购买凭证验证地址
    private static final String certificateUrlTest = "https://sandbox.itunes.apple.com/verifyReceipt";
    @Autowired
    private TencentImRealization tencentImRealization;

    @Resource
    YwpdChargeDetailService ywpdChargeDetailService;

    @Resource
    YwpdMemberService ywpdMemberService;

    /**
     * 接收iOS端发过来的购买凭证
     *
     * @param
     * @throws IOException
     */
    @PostMapping("/api/user/iosRecharge")
    public Response setIapCertificate(@RequestBody JSONObject requestParams) throws IOException {
        String userId = requestParams.getString("userId");
        String certificateCode = requestParams.getString("certificateCode");
        Integer coin = requestParams.getInteger("coin");
        String rmb = requestParams.getString("rmb");
        String url = certificateUrl;
        if (StringUtil.isEmpty(userId) || StringUtil.isEmpty(certificateCode) || StringUtil.isEmpty(rmb) || coin == null) {
            return Response.error(ErrorCode.PARAM_ERROR, "参数错误!");
        }
        try {
            String sendHttpsCoon = sendHttpsCoon(url, certificateCode);
           /* JSONObject json = JSONObject.parseObject(sendHttpsCoon);
            if ("21007".equals(json.get("status").toString())) {
                url = certificateUrlTest;
                sendHttpsCoon = sendHttpsCoon(url, certificateCode);  //发送请求
            }*/
            JSONObject jsonObject = JSONObject.parseObject(sendHttpsCoon);
            if ("0".equals(jsonObject.get("status").toString())) {    //苹果服务器向返回status结果
                JSONArray inapp = (JSONArray) ((JSONObject) jsonObject.get("receipt")).get("in_app");
                if (inapp.size() > 0) { //如果订单状态成功在判断in_app这个字段有没有，没有直接就返回失败了。如果存在的话，遍历整个数组，通过客户端给的transaction_id 来比较
                    JSONObject parseObject = (JSONObject) inapp.get(0);
                    String transaction_id = parseObject.get("transaction_id").toString();
                    YwpdChargeDetail detail = ywpdChargeDetailService.selectByOrderNo(transaction_id);
                    if (null != detail) {
                        return Response.error(ErrorCode.ALREADY_EXIST, "记录已存在!");
                    }
                    YwpdChargeDetail ywpdChargedetail = new YwpdChargeDetail();
                    ywpdChargedetail.setOrderNo(transaction_id);
                    ywpdChargedetail.setUserId(Long.valueOf(userId));
                    ywpdChargedetail.setChargeMode("ios");
                    ywpdChargedetail.setChargeTime(StringUtil.getDateTime());
                    ywpdChargedetail.setCoin(coin);
                    ywpdChargedetail.setRmb(Float.valueOf(rmb));
                    ywpdChargedetail.setContent("陌滋-" + coin + "幸运币");
                    ywpdChargedetail.setStatus("交易成功");
                    ywpdChargeDetailService.addChargeDetail(ywpdChargedetail);
                    //完成支付后，将用户充进的虚拟货币添加到用户数据中
                    ywpdMemberService
                            .updateCoinByUserId(ywpdChargedetail.getCoin(), ywpdChargedetail.getUserId());
                    if (null != ywpdChargedetail && !ywpdChargedetail.getContent().contains("VIP")) {
                        Response msg = new Response();
                        msg.setCode(ImCommand.RECHARGE_NOTICE);
                        msg.setDesc("Hi,你已成功充值" + ywpdChargedetail.getCoin() + "幸运币,可以用来购买会员和礼物。");
                        tencentImRealization.sendmsg(tencentImRealization.generateUserBody(JSON.toJSONString(msg), ywpdChargedetail.getUserId() + ""));
                    }

                }
            }
            return Response.ok(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.error(ErrorCode.INTERNAL_ERROR, "购买凭证验证错误");
        }
    }

    /**
     * 重写X509TrustManager
     */
    private static TrustManager myX509TrustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }
    };

    /**
     * 发送请求
     *
     * @param url
     * @param
     * @return
     */
    private String sendHttpsCoon(String url, String code) {
        if (url.isEmpty()) {
            return null;
        }
        try {
            // 设置SSLContext
            SSLContext ssl = SSLContext.getInstance("SSL");
            ssl.init(null, new TrustManager[]{myX509TrustManager}, null);

            // 打开连接
            HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
            // 设置套接工厂
            conn.setSSLSocketFactory(ssl.getSocketFactory());
            // 加入数据
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-type", "application/json");

            JSONObject obj = new JSONObject();
            obj.put("receipt-data", code);

            BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream());
            buffOutStr.write(obj.toString().getBytes());
            buffOutStr.flush();
            buffOutStr.close();

            // 获取输入流
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();

        } catch (Exception e) {
            return null;
        }
    }
}

